import './index.scss';

import React, { FC, ReactElement, KeyboardEvent, useCallback } from 'react';
import { Input, Button } from '@douyinfe/semi-ui';
import { debounce } from '@/utils/tools';

interface IProps {
  placeholder?: string;
  loading?: boolean;
  keyword: string;
  handleKeywordChange: (newKeyword: string) => void;
  handleSearch: () => void | Promise<void>;
  children?: ReactElement;
}

const KeywordSearch: FC<IProps> = ({
  placeholder = '请输入关键字',
  keyword,
  loading,
  children,

  handleKeywordChange,
  handleSearch
}): ReactElement => {

  const handleKeydown = useCallback(
    debounce((e: KeyboardEvent) => {
      const keyCode = e.key?.toLowerCase?.() || '';
      if (keyCode === 'enter') {
        handleSearch();
      }
    }),
    [handleSearch]
  );

  return (
    <nav className="search-area">
      <Input
        placeholder={placeholder}
        size="default"
        value={keyword}
        onChange={handleKeywordChange}
        style={{ display: 'inline-block', width: 320 }}
        onKeyDown={handleKeydown}
        // showClear
      />
      <Button
        loading={loading}
        onClick={handleSearch}
      >
        查询
      </Button>
      {children}
    </nav>
  );
}

export default KeywordSearch;